<template>
    <div class="app-container stream-setting">
        <!-- 全局配置 -->
        <el-card :header="$t('overall_config')">
            <div>
                <el-row :gutter="24">
                    <el-col :md="3" :sm="6"></el-col>
                    <el-col :md="3" :sm="6">{{ $t('HTTP') }}</el-col>
                    <el-col :md="3" :sm="6">{{ $t('HLS') }}</el-col>
                    <el-col :md="3" :sm="6">{{ $t('RTMP') }}</el-col>
                    <el-col :md="3" :sm="6">{{ $t('RTSP') }}</el-col>
                    <el-col :md="3" :sm="6">{{ $t('multicast') }}</el-col>
                    <el-col :md="3" :sm="6">{{ $t('multicast addr') }}</el-col>
                    <el-col :md="1" :sm="2"></el-col>
                    <el-col :md="2" :sm="4">{{ $t('push') }}</el-col>
                </el-row>
                <!-- 主流 -->
                <all-stream :name="$t('Main protocol')" :data="all"></all-stream>
                <!-- 辅流 -->
                <all-stream :name="$t('Sub protocol')" :data="all_sub"></all-stream>

                <el-divider></el-divider>

                <div class="btns">
                    <el-button type="primary" size="large" @click="setAll">{{ $t('Save to local') }}</el-button>
                    <el-button type="primary" size="large" @click="setGroup">{{ $t('Save to group') }}</el-button>
                </div>
            </div>

        </el-card>

        <el-tabs v-model="activeName" type="border-card" style="margin-top:40px;position: relative;min-height: 300px;">
            <el-tab-pane :label="$t('Stream Config')" name="tab-Stream">
                <tabStream :data="enabledChn"></tabStream>
            </el-tab-pane>
            <el-tab-pane :label="$t('TS Config')" name="tab-TS">
                <tabTS :data="enabledChn"></tabTS>
            </el-tab-pane>
            <el-tab-pane :label="$t('HLS Config')" name="tab-HLS">
                <tabHLS :data="enabledChn"></tabHLS>
            </el-tab-pane>
            <el-tab-pane :label="$t('RTSP Config')" name="tab-RTSP">
                <tabRTSP :data="enabledChn"></tabRTSP>
            </el-tab-pane>
            <el-tab-pane :label="$t('SRT Config')" name="tab-SRT">
                <tabSRT :data="enabledChn"></tabSRT>
            </el-tab-pane>
            <el-tab-pane :label="$t('NDI Config')" name="tab-NDI">
                <tabNDI :data="enabledChn"></tabNDI>
            </el-tab-pane>
            <el-tab-pane :label="$t('Push Config')" name="tab-Push">
                <tabPUSH :data="enabledChn"></tabPUSH>
            </el-tab-pane>
            <el-tab-pane :label="$t('Play URL')" name="tab-URL">
                <tabURL :data="epg"></tabURL>
            </el-tab-pane>
        </el-tabs>

        <div class="btns">
            <el-button type="primary" size="large" @click="save">{{ $t('Save') }}</el-button>
        </div>
        <!-- 群组同步 -->
        <GroupList ref="GroupListRef" @groupSync="groupSync"></GroupList>
    </div>
</template>
  
<script setup name="stream-setting">
import { ElMessageBox } from 'element-plus'
import modal from "@/plugins/modal.js"
import GroupList from '@/components/GroupList/index.vue'
import RPC from "@/api/rpc"
import getJson from "@/api/getJson"
import i18n from '@/lang'
import { cloneDeep } from 'lodash'
import { nextTick } from 'vue'
const router = useRouter();

console.log(router.getRoutes());

import allStream from './components/allStream.vue'
import tabStream from './components/tab-stream.vue'
import tabTS from './components/tab-TS.vue'
import tabHLS from './components/tab-HLS.vue'
import tabRTSP from './components/tab-RTSP.vue'
import tabSRT from './components/tab-SRT.vue'
import tabNDI from './components/tab-NDI.vue'
import tabPUSH from './components/tab-PUSH.vue'
import tabURL from './components/tab-URL.vue'
import config_json_bak from '@/config/config_json_bak.js'
// modal.loading('Loading...')

let hardware = reactive({})
let config = reactive([])
let rtspAuth = 0

function handleInit() {
    // console.log('开始handleInit')
    config.length = 0
    let p1 = getJson('/config/hardware.json')
    let p2 = getJson('/config/config.json')

    Promise.all([p1, p2]).then(res => {
        let [r1, r2] = res
        hardware = Object.assign(hardware, r1.data)
        config = config.concat(r2.data)

        rtspAuth = hardware.function.rtspAuth ? 1 : -1

        // console.log('handleInit config =========== ', config)

        setData()

    }).finally(() => {
        nextTick(() => {
            modal.closeLoading()
        })
    })
}
handleInit('load')


let all = reactive({})
let all_sub = reactive({})

let activeName = ref('tab-Stream')
let enabledChn = reactive([]);       // tab 1-7  --> setData()
let epg = reactive([]);              // tab 8 --> getEPG()

function setData() {
    
    if (config.length > 0) {
        enabledChn.length = 0
        config.forEach(conf => {
            if (conf.hasOwnProperty("stream") && rtspAuth > 0) {
                let rtsp = conf.stream.rtsp;
                if (!rtsp.hasOwnProperty("enable")) {
                    rtsp = {
                        enable: rtsp,
                        name: "admin",
                        passwd: "admin",
                        auth: false
                    }
                    conf.stream.rtsp = rtsp;
                }

                if (!conf.stream.hasOwnProperty("suffix"))
                    conf.stream.suffix = "stream" + conf.id;
            }
            if (conf.hasOwnProperty("stream2") && rtspAuth > 0) {
                var rtsp = conf.stream2.rtsp;
                if (!rtsp.hasOwnProperty("enable")) {
                    rtsp = {
                        enable: rtsp,
                        name: "admin",
                        passwd: "admin",
                        auth: false
                    }
                    conf.stream2.rtsp = rtsp;
                }
                if (!conf.stream2.hasOwnProperty("suffix"))
                    conf.stream2.suffix = "sub" + conf.id;
            }
            if (conf.enable || conf.enable2) {
                enabledChn.push(conf);
            }
        })
        
        all = Object.assign(all, cloneDeep(config[0].stream))
        all_sub = Object.assign(all_sub, cloneDeep(config[0].stream2))

        getSpeed()
    }

    nextTick(() => {
        modal.closeLoading()
    })
}

let timer
function getSpeed() {
    RPC("enc.getPushSpeed").then(res => {
        let result = res.data.result

        enabledChn.forEach((item, index) => {
            item.stream.push.speed = result[index * 2]
            item.stream2.push.speed = result[index * 2 + 1]
        })

    }).finally(() => {
        clearTimeout(timer)
        timer = setTimeout(getSpeed, 2000);
    })
}

/* 获取 epg（tab8） 数据 开始 */
let portCfg = {}
getJson("config/port.json").then(res => {
    portCfg = res.data;
    getEPG();
})
function getEPG() {
    RPC("enc.getEPG", null).then(res => {
        let result = res.data.result
        epg = result.length ? result.map(item => {
            item.url = transURL(item.url)
            item.url2 = transURL(item.url2)
            return item
        }) : []
    })
}
function transURL(str) {
    var ret = "";
    var ip = window.location.hostname;
    var list = str.split("|");
    for (var i = 0; i < list.length; i++) {
        var url = list[i];
        if (url.indexOf("http") == 0) {
            if (url.indexOf("///live") > 0) {
                var port = getport(portCfg.http, "http");
                var port2 = getport(portCfg.httpts, "httpts");
                if (port != "" || port2 != "") {
                    if (port != "" && port2 == "")
                        port2 = ":" + portCfg.httpts[0];
                    url = url.replace("///live", "//" + ip + port2);
                } else {
                    url = url.replace("///", "//" + ip + "/");
                }
            }
            else {
                var port = getport(portCfg.http, "http");
                url = url.replace("///", "//" + ip + port + "/");
            }
        }
        else if (url.indexOf("rtmp") == 0) {
            var port = getport(portCfg.rtmp, "rtmp");
            url = url.replace("///", "//" + ip + port + "/");
        }
        else if (url.indexOf("rtsp") == 0) {
            var port = getport(portCfg.rtsp, "rtsp");
            if (url.indexOf("@/") > 0)
                url = url.replace("@/", "@" + ip + port + "/");
            else
                url = url.replace("///", "//" + ip + port + "/");
        }
        else if (url.indexOf("srt") == 0) {
            url = url.replace("//:", "//" + ip + ":");
        }

        ret += url + (i == list.length - 1 ? '' : '\n');
    }
    return ret;
}
function getport(list, type) {
    if (list[2] != list[0])
        return ":" + list[2];
    else if (list[1] != list[0])
        return ":" + list[1];
    else if ((type == "http" && list[0] == 80) || (type == "rtsp" && list[0] == 554) || (type == "rtmp" && list[0] == 1935) || (type == "httpts" && list[0] == 8090))
        return "";
    else
        return ":" + list[0];
}
/* 获取 epg（tab8） 数据 结束 */


/* setAll 开始 */
function setAll() {

    let all_tmp = fmt(cloneDeep(all))
    let all_sub_tmp = fmt(cloneDeep(all_sub))

    let streamInfo = getInfo(all_tmp.udp)
    let stream2Info = getInfo(all_sub_tmp.udp)

    config.forEach((conf, i) => {
        Object.assign(conf.stream, cloneDeep(all_tmp))
        Object.assign(conf.stream2, cloneDeep(all_sub_tmp))

        if (streamInfo.ipPlus) {
            conf.stream.udp.ip = streamInfo.ipBase1 + (streamInfo.ipBase2 + i);
        }
        if (streamInfo.portPlus) {
            conf.stream.udp.port = streamInfo.portBase + i;
        }

        if (stream2Info.ipPlus) {
            conf.stream2.udp.ip = stream2Info.ipBase1 + (stream2Info.ipBase2 + i);
        }
        if (stream2Info.portPlus) {
            conf.stream2.udp.port = stream2Info.portBase + i;
        }
    })

    console.log('setAll ============ ', config)
    nextTick(() => {
        save()
    })

}
function fmt(obj) {
    obj.udp.ip = obj.udp.ip_port.split(':')[0]
    obj.udp.port = obj.udp.ip_port.split(':')[1]
    delete obj.udp.ip_port
    return obj
}
function getInfo(obj) {
    var ipPlus = false;
    var portPlus = false;
    var ipBase1 = "";
    var ipBase2 = 0;
    var portBase = 0;

    if (obj.ip.indexOf("+") > 0) {
        var ip = obj.ip;
        ip = ip.replace("+", "");
        ipPlus = true;

        var n = ip.lastIndexOf(".");
        ipBase1 = ip.substr(0, n + 1);
        ipBase2 = Number(ip.substr(n + 1));
    }
    if (obj.port.toString().indexOf("+") > 0) {
        var port = obj.port;
        port = Number(port.replace("+", ""));
        portPlus = true;
        portBase = Number(port);
    }

    return { ipPlus, portPlus, ipBase1, ipBase2, portBase }

}
/* setAll 结束 */

// save
function save() {

    config.forEach(conf => {
        let epgItem = epg.find(item => (conf.id == item.id && item.hasOwnProperty("mainSuffix") && item.hasOwnProperty("subSuffix")))
        if (epgItem) {
            conf.stream.suffix = epgItem.mainSuffix;
            conf.stream2.suffix = epgItem.subSuffix;
        }
    })

    // let config = config_json_bak

    console.log('save ======= ', config)

    RPC("enc.update", [JSON.stringify(config, null, 2)]).then(res => {
        modal.msgSuccess(i18n.global.t('Save success'))
        nextTick(() => {
            handleInit();
        })
    }).catch(() => {
        modal.msgError(i18n.global.t('Save failed'))
    })
}

// 同步群组
const GroupListRef = ref()
function setGroup() {
    GroupListRef.value.open()
}
function groupSync(groupList) {
    let all_tmp = fmt(cloneDeep(all))
    let all_sub_tmp = fmt(cloneDeep(all_sub))

    let streamInfo = getInfo(all_tmp.udp)
    let stream2Info = getInfo(all_sub_tmp.udp)

    let cfg = {}
    let cfg2 = {}
    let map = {}
    let proArr = []
    if (groupList.length > 0) {
        groupList.forEach((item, i) => {
            Object.assign(cfg, cloneDeep(all_tmp))
            Object.assign(cfg2, cloneDeep(all_sub_tmp))

            if (streamInfo.ipPlus) {
                cfg.udp.ip = streamInfo.ipBase1 + (streamInfo.ipBase2 + i * 20) + "+";
            }
            if (streamInfo.portPlus) {
                cfg.udp.port = (streamInfo.portBase + i * 20) + "+";
            }

            if (stream2Info.ipPlus) {
                cfg2.udp.ip = stream2Info.ipBase1 + (stream2Info.ipBase2 + i * 20) + "+";
            }
            if (stream2Info.portPlus) {
                cfg2.udp.port = (stream2Info.portBase + i * 20) + "+";
            }

            map = { cfg, cfg2 }

            console.log( [item.mac, map])

            item.status = 'pending'
            proArr.push(RPC("group.callSetStream", [item.mac, map]))
        })
    }
    Promise.all(proArr).then(res => {
        if (res.length > 0) {
            res.forEach((r, index) => {
                groupList[index].status = r.data.result ? 'success' : 'error'
            })
        }
        handleInit();
    })
}
onBeforeUnmount(() => {
    clearTimeout(timer)
})
</script>
  
<style scoped lang="scss">
.stream-setting {
    .btns {
        text-align: center;
        margin-top: 20px;
    }
}
</style>
  
  